package com.damage.purchase_dept.oa.makePurchasePlan;

import com.damage.common.entity.PurchasePlan;
import com.damage.common.exception.IncorrectPriceException;
import com.damage.common.oa.makePurchasePlan.MakePurchasePlanConfig;
import com.damage.purchase_dept.service.IPurchasePlanService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class ReApplyService {

    @Autowired
    private IPurchasePlanService purchasePlanService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Transactional
    public PurchasePlan reApplyPurchasePlan(String taskId, PurchasePlan purchasePlan){
        //更新采购计划
        try {
            purchasePlanService.update(purchasePlan);
        } catch (IncorrectPriceException e) {
            e.printStackTrace();
        }
        taskService.setVariable(taskId, MakePurchasePlanConfig.RE_APPLY,true);
        taskService.complete(taskId);
        return purchasePlan;
    }

    @Transactional
    public PurchasePlan cancelApplyPurchasePlan(String taskId){
        //关联业务实体
        Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        String businessKey = processInstance.getBusinessKey();

        //查找要取消的采购计划
        PurchasePlan purchasePlan = purchasePlanService.findById(Integer.parseInt(businessKey));
        //删除采购计划
        purchasePlanService.deleteById(Integer.parseInt(businessKey));

        return purchasePlan;
    }
}
